package cn.sisyphe.framework.web.exception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.text.MessageFormat;
import java.util.Arrays;

/**
 * Created by heyong on 2017/11/24 17:08
 * Description: 禁止访问异常
 * @author heyong
 */
@ResponseStatus(HttpStatus.FORBIDDEN)
public class AccessDeniedException extends RuntimeException {

    public AccessDeniedException(String errorCode, String errorMessage) {
        super(MessageFormat.format("*[{0}] {1}", errorCode, errorMessage));
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
    }

    public AccessDeniedException(String errorCode, String pattern, String[] formatMessage, Object... payload) {
        super(MessageFormat.format("*[{0}] {1} {2}", errorCode, MessageFormat.format(pattern, formatMessage), Arrays.toString(payload)));
        this.errorCode = errorCode;
        this.errorMessage = MessageFormat.format(pattern, formatMessage);
        this.formatMessage = formatMessage;
        this.payload = payload;
    }

    /**
     * 错误代码
     */
    private String errorCode;
    /**
     * 错误说明,此说明只显示在后端、日志中，不显示在前端，此处由 GlobalExceptionHandler 处理
     */
    private String errorMessage;
    /**
     * 抛出对象,在日志中记录
     */
    private Object[] payload;

    /**
     * 格式化错误信息
     */
    private String[] formatMessage;


    public String getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        if (formatMessage != null){
            this.errorMessage = MessageFormat.format(errorMessage, formatMessage);
        }else {
            this.errorMessage = errorMessage;
        }
    }

    public Object[] getPayload() {
        return payload;
    }

    public void setPayload(Object[] payload) {
        this.payload = payload;
    }

    @Override
    public String toString() {
        return "AccessDeniedException{" +
                "errorCode='" + errorCode + '\'' +
                ", errorMessage='" + errorMessage + '\'' +
                ", payload=" + Arrays.toString(payload) +
                ", formatMessage=" + Arrays.toString(formatMessage) +
                '}';
    }
}
